<template>
  <Header />
  <div class="payment-view">
    <div class="payment-container">
      <!-- 页面标题 -->
      <div class="page-header">
        <h1>订单支付</h1>
        <div class="step-indicator">
          <div class="step">1. 确认订单</div>
          <div class="step-line"></div>
          <div class="step">2. 选择地址</div>
          <div class="step-line"></div>
          <div class="step active">3. 支付</div>
        </div>
      </div>

      <!-- 加载状态 -->
      <div v-if="loading" class="loading">
        <div class="spinner"></div>
        加载中...
      </div>

      <!-- 错误状态 -->
      <div v-else-if="error" class="error-message">
        <div class="error-icon">⚠️</div>
        <div class="error-text">{{ errorMessage }}</div>
        <button class="retry-btn" @click="initPayment">重试</button>
      </div>

      <!-- 支付内容 -->
      <div v-else class="payment-content">
        <!-- 订单信息 -->
        <div class="order-info">
          <h2>订单信息</h2>
          <div class="order-details">
            <div class="detail-item">
              <span class="label">订单号：</span>
              <span class="value">{{ orderInfo.orderId }}</span>
            </div>
            <div class="detail-item">
              <span class="label">订单金额：</span>
              <span class="value amount">¥{{ amount?.toFixed(2) }}</span>
            </div>
            <div class="detail-item">
              <span class="label">创建时间：</span>
              <span class="value">{{ formatDate(orderInfo.createTime) }}</span>
            </div>
          </div>
        </div>

        <!-- 支付方式选择 -->
        <div v-if="!paymentStarted" class="payment-methods">
          <h2>选择支付方式</h2>
          <div class="method-list">
            <div v-for="method in availablePaymentMethods" :key="method.id" class="payment-method"
              :class="{ active: selectedPaymentMethod === method.id }" @click="selectPaymentMethod(method.id)">
              <div class="method-icon">{{ method.icon }}</div>
              <div class="method-info">
                <div class="method-name">{{ method.name }}</div>
                <div class="method-desc">{{ method.description }}</div>
              </div>
              <div class="method-check">
                <div class="check-icon" v-if="selectedPaymentMethod === method.id">✓</div>
              </div>
            </div>
          </div>
        </div>

        <!-- 支付状态 -->
        <div v-if="paymentStarted" class="payment-status">
          <div class="status-content">
            <div class="status-icon">
              <div v-if="paymentStatus === 'processing'" class="spinner"></div>
              <div v-else-if="paymentStatus === 'success'" class="success-icon">✓</div>
              <div v-else-if="paymentStatus === 'failed'" class="error-icon">✗</div>
            </div>
            <div class="status-text">
              <h3>{{ getStatusText() }}</h3>
              <p>{{ getStatusDescription() }}</p>
            </div>
          </div>

          <!-- 支付二维码（模拟） -->
          <div v-if="paymentStatus === 'processing' && selectedPaymentMethod === 'wechat'" class="qr-code">
            <div class="qr-placeholder">
              <div class="qr-icon">📱</div>
              <p>请使用微信扫码支付</p>
              <div class="qr-code-mock"></div>
            </div>
          </div>

          <!-- 支付表单（模拟） -->
          <div v-if="paymentStatus === 'processing' && selectedPaymentMethod === 'bank'" class="payment-form">
            <div class="form-group">
              <label>银行卡号</label>
              <input type="text" v-model="bankCardNumber" placeholder="请输入银行卡号" maxlength="19">
            </div>
            <div class="form-row">
              <div class="form-group">
                <label>有效期</label>
                <input type="text" v-model="cardExpiry" placeholder="MM/YY" maxlength="5">
              </div>
              <div class="form-group">
                <label>CVV</label>
                <input type="text" v-model="cvv" placeholder="CVV" maxlength="3">
              </div>
            </div>
            <div class="form-group">
              <label>持卡人姓名</label>
              <input type="text" v-model="cardholderName" placeholder="请输入持卡人姓名">
            </div>
          </div>
        </div>

        <!-- 支付按钮 -->
        <div class="payment-actions">
          <button v-if="!paymentStarted" class="pay-btn" @click="startPayment" :disabled="!selectedPaymentMethod">
            立即支付 ¥{{ amount?.toFixed(2) }}
          </button>

          <button v-if="paymentStatus === 'processing' && selectedPaymentMethod === 'bank'" class="pay-btn"
            @click="confirmBankPayment" :disabled="!isBankFormValid">
            确认支付
          </button>

          <button v-if="paymentStatus === 'failed'" class="retry-pay-btn" @click="retryPayment">
            重新支付
          </button>

          <button v-if="paymentStatus === 'success'" class="view-order-btn" @click="viewOrder">
            查看订单
          </button>
        </div>

        <!-- 支付提示 -->
        <div class="payment-tips">
          <h3>支付说明</h3>
          <ul>
            <li>支付成功后，订单将自动发货</li>
            <li>如遇支付问题，请联系客服</li>
            <li>支付金额包含商品费用和运费</li>
          </ul>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import Header from '../Header.vue';
import { useStore } from 'vuex';
import { computed, onMounted, ref } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { getOrderDetail, payOrder } from '@/api/order';
import { safeApiCall, getResponseData, isResponseSuccess } from '@/utils/apiHelper';

export default {
  name: 'PaymentView',
  components: {
    Header
  },
  setup() {
    const store = useStore();
    const router = useRouter();
    const route = useRoute();

    const loading = ref(false);
    const error = ref(false);
    const errorMessage = ref('');
    const orderInfo = ref({});
    const selectedPaymentMethod = ref('');
    const paymentStarted = ref(false);
    const paymentStatus = ref(''); // processing, success, failed

    // 新增：从路由query参数获取金额和支付方式
    const amount = computed(() => {
      return route.query.amount ? Number(route.query.amount) : orderInfo.value.totalAmount;
    });
    const paymentMethod = computed(() => {
      return route.query.method ? route.query.method : orderInfo.value.paymentMethod;
    });

    // 银行卡支付表单
    const bankCardNumber = ref('');
    const cardExpiry = ref('');
    const cvv = ref('');
    const cardholderName = ref('');

    const currentUser = computed(() => store.state.currentUser);

    // 可用支付方式
    const availablePaymentMethods = [
      {
        id: 'alipay',
        name: '支付宝',
        icon: '💰',
        description: '推荐使用支付宝支付'
      },
      {
        id: 'wechat',
        name: '微信支付',
        icon: '💳',
        description: '使用微信扫码支付'
      },
      {
        id: 'bank',
        name: '银行卡',
        icon: '🏦',
        description: '支持各大银行'
      }
    ];

    // 获取支付方式名称
    const getPaymentMethodName = (methodId) => {
      const method = availablePaymentMethods.find(m => m.id === methodId);
      return method ? method.name : '未知';
    };

    // 格式化日期
    const formatDate = (dateString) => {
      if (!dateString) return '';
      const date = new Date(dateString);
      return date.toLocaleString('zh-CN');
    };

    // 验证银行卡表单
    const isBankFormValid = computed(() => {
      return bankCardNumber.value.length >= 16 &&
        cardExpiry.value.length === 5 &&
        cvv.value.length === 3 &&
        cardholderName.value.trim().length > 0;
    });

    // 获取状态文本
    const getStatusText = () => {
      switch (paymentStatus.value) {
        case 'processing':
          return '支付处理中...';
        case 'success':
          return '支付成功！';
        case 'failed':
          return '支付失败';
        default:
          return '';
      }
    };

    // 获取状态描述
    const getStatusDescription = () => {
      switch (paymentStatus.value) {
        case 'processing':
          return '请完成支付操作，支付成功后页面将自动跳转';
        case 'success':
          return '您的订单已支付成功，我们将尽快为您发货';
        case 'failed':
          return '支付过程中出现错误，请重新尝试';
        default:
          return '';
      }
    };

    // 初始化支付页面
    const initPayment = async () => {
      loading.value = true;
      error.value = false;

      try {
        const orderId = route.params.orderId;
        if (!orderId) {
          throw new Error('订单ID不能为空');
        }

        const result = await safeApiCall(
          () => getOrderDetail(orderId),
          '获取订单信息失败'
        );

        if (result.success) {
          orderInfo.value = result.data || {};
          // 新增：如果query参数有amount/method，赋值到orderInfo
          if (route.query.amount) orderInfo.value.totalAmount = Number(route.query.amount);
          if (route.query.method) orderInfo.value.paymentMethod = route.query.method;
          selectedPaymentMethod.value = paymentMethod.value || 'alipay';
        } else {
          throw new Error(result.message);
        }
      } catch (err) {
        console.error('初始化支付失败:', err);
        error.value = true;
        errorMessage.value = err.message || '初始化支付失败';
      } finally {
        loading.value = false;
      }
    };

    // 选择支付方式
    const selectPaymentMethod = (methodId) => {
      selectedPaymentMethod.value = methodId;
    };

    // 开始支付
    const startPayment = async () => {
      if (!selectedPaymentMethod.value) {
        alert('请选择支付方式');
        return;
      }

      paymentStarted.value = true;
      paymentStatus.value = 'processing';

      try {
        if (selectedPaymentMethod.value === 'alipay') {
          // 调用后端支付宝接口，拿到html并新窗口打开
          const html = await payOrder(orderInfo.value.orderId);
          const payWindow = window.open('', '_blank');
          payWindow.document.write(html);
          payWindow.document.close();
          // 不直接设置为success，等待用户支付完成后手动刷新或轮询
        } else if (selectedPaymentMethod.value === 'wechat') {
          // 微信支付 - 显示二维码
        } else if (selectedPaymentMethod.value === 'bank') {
          // 银行卡支付 - 显示表单
        }
      } catch (err) {
        console.error('支付失败:', err);
        paymentStatus.value = 'failed';
      }
    };

    // 确认银行卡支付
    const confirmBankPayment = async () => {
      if (!isBankFormValid.value) {
        alert('请完善银行卡信息');
        return;
      }

      try {
        // 将支付方式字符串转换为数字类型
        const getPaymentTypeNumber = (method) => {
          switch (method) {
            case 'alipay': return 1;
            case 'wechat': return 2;
            case 'bank': return 3;
            default: return 1; // 默认为支付宝
          }
        };
        
        const paymentData = {
          orderId: orderInfo.value.orderId,
          paymentType: getPaymentTypeNumber(selectedPaymentMethod.value),
          amount: amount.value,
          cardInfo: {
            cardNumber: bankCardNumber.value,
            expiry: cardExpiry.value,
            cvv: cvv.value,
            cardholderName: cardholderName.value
          }
        };

        const result = await safeApiCall(
          () => payOrder(paymentData),
          '支付失败'
        );

        if (result.success) {
          paymentStatus.value = 'success';
        } else {
          throw new Error(result.message);
        }
      } catch (err) {
        console.error('银行卡支付失败:', err);
        paymentStatus.value = 'failed';
      }
    };

    // 重新支付
    const retryPayment = () => {
      paymentStarted.value = false;
      paymentStatus.value = '';
    };

    // 查看订单
    const viewOrder = () => {
      router.push('/orders');
    };

    onMounted(() => {
      if (!currentUser.value) {
        router.push('/login');
        return;
      }
      initPayment();
    });

    return {
      loading,
      error,
      errorMessage,
      orderInfo,
      selectedPaymentMethod,
      paymentStarted,
      paymentStatus,
      bankCardNumber,
      cardExpiry,
      cvv,
      cardholderName,
      availablePaymentMethods,
      isBankFormValid,
      getPaymentMethodName,
      formatDate,
      getStatusText,
      getStatusDescription,
      initPayment,
      selectPaymentMethod,
      startPayment,
      confirmBankPayment,
      retryPayment,
      viewOrder,
      amount,
      paymentMethod
    };
  }
};
</script>

<style scoped>
.payment-view {
  background-color: #f5f7fa;
  min-height: 100vh;
  padding: 2rem 0;
}

.payment-container {
  max-width: 800px;
  margin: 0 auto;
  padding: 0 2rem;
}

.page-header {
  margin-bottom: 2rem;
}

.page-header h1 {
  font-size: 1.8rem;
  font-weight: 600;
  color: #333;
  margin-bottom: 1rem;
}

.step-indicator {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 2rem;
}

.step {
  padding: 0.5rem 1rem;
  background-color: #f0f0f0;
  border-radius: 20px;
  font-size: 0.9rem;
  color: #666;
}

.step.active {
  background-color: #1890ff;
  color: white;
}

.step-line {
  width: 60px;
  height: 2px;
  background-color: #ddd;
  margin: 0 1rem;
}

.loading {
  text-align: center;
  padding: 3rem;
  color: #666;
}

.spinner {
  border: 3px solid #f3f3f3;
  border-top: 3px solid #1890ff;
  border-radius: 50%;
  width: 30px;
  height: 30px;
  animation: spin 1s linear infinite;
  margin: 0 auto 1rem;
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }

  100% {
    transform: rotate(360deg);
  }
}

.error-message {
  text-align: center;
  padding: 3rem;
  background-color: #fff1f0;
  border-radius: 8px;
}

.error-icon {
  font-size: 2rem;
  margin-bottom: 1rem;
}

.error-text {
  color: #f5222d;
  margin-bottom: 1rem;
}

.retry-btn {
  padding: 0.5rem 1.5rem;
  background-color: #f5222d;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.payment-content>div {
  background-color: white;
  border-radius: 8px;
  padding: 1.5rem;
  margin-bottom: 1.5rem;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.payment-content h2 {
  font-size: 1.2rem;
  font-weight: 600;
  color: #333;
  margin-bottom: 1rem;
}

/* 订单信息样式 */
.order-details {
  display: grid;
  gap: 1rem;
}

.detail-item {
  display: flex;
  justify-content: space-between;
  padding: 0.5rem 0;
  border-bottom: 1px solid #eee;
}

.detail-item:last-child {
  border-bottom: none;
}

.label {
  color: #666;
  font-weight: 500;
}

.value {
  color: #333;
  font-weight: 600;
}

.value.amount {
  color: #f5222d;
  font-size: 1.1rem;
}

/* 支付方式样式 */
.method-list {
  display: grid;
  gap: 1rem;
}

.payment-method {
  border: 2px solid #eee;
  border-radius: 8px;
  padding: 1rem;
  cursor: pointer;
  transition: all 0.3s;
  display: flex;
  align-items: center;
  position: relative;
}

.payment-method:hover {
  border-color: #1890ff;
}

.payment-method.active {
  border-color: #1890ff;
  background-color: #f0f8ff;
}

.method-icon {
  font-size: 1.5rem;
  margin-right: 1rem;
}

.method-info {
  flex: 1;
}

.method-name {
  font-weight: 600;
  margin-bottom: 0.25rem;
}

.method-desc {
  color: #666;
  font-size: 0.9rem;
}

.method-check {
  width: 20px;
  height: 20px;
  border: 2px solid #ddd;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.check-icon {
  color: #1890ff;
  font-weight: bold;
}

/* 支付状态样式 */
.payment-status {
  text-align: center;
}

.status-content {
  margin-bottom: 2rem;
}

.status-icon {
  margin-bottom: 1rem;
}

.success-icon {
  width: 60px;
  height: 60px;
  background-color: #52c41a;
  color: white;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 2rem;
  margin: 0 auto;
}

.error-icon {
  width: 60px;
  height: 60px;
  background-color: #f5222d;
  color: white;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 2rem;
  margin: 0 auto;
}

.status-text h3 {
  font-size: 1.5rem;
  margin-bottom: 0.5rem;
  color: #333;
}

.status-text p {
  color: #666;
  line-height: 1.5;
}

/* 二维码样式 */
.qr-code {
  margin: 2rem 0;
}

.qr-placeholder {
  text-align: center;
}

.qr-icon {
  font-size: 3rem;
  margin-bottom: 1rem;
}

.qr-code-mock {
  width: 200px;
  height: 200px;
  background-color: #f0f0f0;
  border: 2px dashed #ddd;
  margin: 1rem auto;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #999;
}

/* 支付表单样式 */
.payment-form {
  max-width: 400px;
  margin: 0 auto;
}

.form-group {
  margin-bottom: 1rem;
}

.form-row {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 1rem;
}

.form-group label {
  display: block;
  margin-bottom: 0.5rem;
  color: #333;
  font-weight: 500;
}

.form-group input {
  width: 100%;
  padding: 0.75rem;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 1rem;
}

.form-group input:focus {
  outline: none;
  border-color: #1890ff;
}

/* 支付按钮样式 */
.payment-actions {
  text-align: center;
  padding: 2rem 0;
}

.pay-btn,
.retry-pay-btn,
.view-order-btn {
  padding: 1rem 3rem;
  border: none;
  border-radius: 8px;
  font-size: 1.1rem;
  font-weight: 600;
  cursor: pointer;
  transition: background-color 0.3s;
}

.pay-btn {
  background-color: #f5222d;
  color: white;
}

.pay-btn:hover {
  background-color: #d32029;
}

.pay-btn:disabled {
  background-color: #ccc;
  cursor: not-allowed;
}

.retry-pay-btn {
  background-color: #1890ff;
  color: white;
  margin-right: 1rem;
}

.retry-pay-btn:hover {
  background-color: #096dd9;
}

.view-order-btn {
  background-color: #52c41a;
  color: white;
}

.view-order-btn:hover {
  background-color: #389e0d;
}

/* 支付提示样式 */
.payment-tips {
  background-color: #f6ffed;
  border: 1px solid #b7eb8f;
  border-radius: 8px;
  padding: 1.5rem;
}

.payment-tips h3 {
  color: #52c41a;
  margin-bottom: 1rem;
}

.payment-tips ul {
  list-style: none;
  padding: 0;
}

.payment-tips li {
  color: #666;
  margin-bottom: 0.5rem;
  padding-left: 1rem;
  position: relative;
}

.payment-tips li:before {
  content: "•";
  color: #52c41a;
  position: absolute;
  left: 0;
}

@media (max-width: 768px) {
  .payment-container {
    padding: 0 1rem;
  }

  .step-indicator {
    flex-direction: column;
    gap: 1rem;
  }

  .step-line {
    width: 2px;
    height: 20px;
  }

  .form-row {
    grid-template-columns: 1fr;
  }

  .payment-actions {
    display: flex;
    flex-direction: column;
    gap: 1rem;
  }

  .retry-pay-btn {
    margin-right: 0;
  }
}
</style>